import { useState, useEffect, useMemo, Key, createContext } from "react";
import { Button, Table, message, Select, Form } from 'antd';
import { uuid } from '@inbiz/utils';
import { useInbizRouter } from '@inbiz/hooks';
import { EditableRow, EditableCell } from './EditCell';
import { getVariateList } from '../../server';
import './style.less';

const ExchangeVariableEditableContext = createContext<any>(null);
export { ExchangeVariableEditableContext };

export default function ExchangeVariable(props: any) {
    const { processId, subProcessId, value, onChange } = props;
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<any[]>(value || []);
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
    const [parentData, setParentData] = useState<any[]>([]);
    const [childData, setChildData] = useState<any[]>([{ id: 'initiator', varName: 'initiator' }]);
    const [curId, setCurId] = useState<string>('');
    const history = useInbizRouter();
    const [form] = Form.useForm();

    useEffect(() => {
        let _value = [];
        try {
            _value = value ? typeof value === 'string' ? JSON.parse(value) : value : [];
        } catch (error) {
            console.log(error);
        }
        setData(_value);
    }, [value]);

    useEffect(() => {
        setLoading(true);
        getVariateList({ processId }).then((res) => {
            if (res?.code == '200') {
                if (res?.details?.rows) {
                    setParentData(res?.details?.rows);
                }
            } else {
                message.error(res?.message);
            };
            setLoading(false);
        }).catch((error) => {
            message.error(error);
            setLoading(false);
        })
    }, []);

    useEffect(() => {
        if (subProcessId) {
            getVariateList({ processId: subProcessId }).then((res) => {
                if (res?.code == '200') {
                    if (res?.details?.rows) {
                        setChildData([{ id: 'initiator', varName: 'initiator' }, ...res?.details?.rows]);
                    }
                } else {
                    message.error(res?.message);
                }
            }).catch((error) => {
                message.error(error);
            })
        } else {
            setData([]);
            onChange([]);
        }
    }, [subProcessId]);

    const defaultColumns: any = useMemo(() => {
        return [
            {
                title: '父流程输入变量',
                dataIndex: 'pin',
                key: 'pin',
                editable: true,
            },
            {
                title: '子流程接收变量',
                dataIndex: 'pout',
                key: 'pout',
                editable: true,
            },
            {
                title: '父流程接收变量',
                dataIndex: 'sout',
                key: 'sout',
                editable: true,
            },
        ]
    }, [parentData, childData, data]);

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const handleSave = (row: any) => {
        const newData: any = [...data];
        const index = newData.findIndex((item: { id: string }) => row.id === item.id);
        const item: any = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        setData(newData);
        onChange(newData);
    };

    const columns: any = useMemo(() => {
        return defaultColumns.map((col: { editable: any; dataIndex: any; title: any; required: any; }) => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: (record: any) => ({
                    record,
                    editable: col.editable,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    required: col.required,
                    variateId: curId,
                    setNowKey: (e: any) => setCurId(e),
                    handleSave,
                    parentList: parentData,
                    childList: childData,
                }),
            };
        })
    }, [curId, defaultColumns, parentData, childData]);

    const onSelectChange = (newSelectedRowKeys: Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    const addVariableRow = () => {
        if (!subProcessId) {
            message.warning('请先选择子流程');
            return;
        }
        let _data = [...data];
        _data = _data?.concat({ id: 'exchangeVariable' + uuid(20, 60), pin: '', pout: '', sout: '' });
        setData(_data);
        onChange(_data);
    };

    const delVariable = () => {
        if (!subProcessId) {
            message.warning('请先选择子流程');
            return;
        }
        if (selectedRowKeys.length === 0) {
            message.warning('请选中要删除的变量');
        } else {
            let _data = data.filter((item: any) => !selectedRowKeys.includes(item.id))
            setData(_data);
            onChange(_data);
            setSelectedRowKeys([]);
        }
    };

    return (
        <div className='process-designer-exchange-variable'>
            <>
                <div className='process-designer-exchange-variable-buttons'>
                    <Button type='primary' onClick={addVariableRow}>添加</Button>
                    <Button danger onClick={delVariable}>删除</Button>
                </div>
                <div className='process-designer-exchange-variable-table'>
                    <Form form={form}>
                        <ExchangeVariableEditableContext.Provider value={form}>
                            <Table
                                columns={columns}
                                components={components}
                                dataSource={data}
                                pagination={false}
                                rowSelection={rowSelection}
                                size="small"
                                rowKey="id"
                                bordered
                                loading={loading}
                                rowClassName={'process-designer-exchange-variable-table-row'}
                            />
                        </ExchangeVariableEditableContext.Provider>
                    </Form>
                </div>
            </>
        </div>
    )
}